<?php
/**
 * 通行证服务
 */
class PassportService extends Service {
	//static C('COOKIE_FLAG_USER') = 'QUICK_PARTNER_GF';
	//static $COOKIE_FLAG_USER 	= 'QUICK_USER_GF';
	/**
	 * 验证用户是否已登录
	 * @return boolean
	 */
	public function isLogged(){
		$_cookie_user		=	t(cookie(C('COOKIE_FLAG_USER')));
		$_session_user		=	t($_SESSION['uname']);
		$_session_user_id	=	intval($_SESSION['mid']);
		
		// 验证本地系统登录
		if($_session_user_id){
			return true;
		}elseif ($_cookie_user){
			return $this->cookieLoginLocal($_cookie_user);
		}else{
			return false;
		}
	}

	/**
	 * 根据Email和未加密的密码获取本地用户 (密码为false时只验证Email)
	 * @param string         $email
	 * @param string|boolean $password
	 */
	public function getLocalUser($email,$password=false) {
		$map['email']		 = $email;
		if($password !== false) {
			$map['password'] = md5($password);
		}
		//$map['role']		 = 'user';
		$user = model('User')->where($map)->find();
		if(!$user){
			return false;
		}else{
			return $user;
		}
	}

	/**
	 * 使用cookie登陆
	 * 
	 * @param string $cookieId
	 * @return boolean
	 */
	public function cookieLoginLocal($cookieId){
		$cookieId = explode( '.', base64_decode($cookieId) );
		//dump($cookieId);
		if ($cookieId[0] !== 'USER') {
			return false;
		}else {
			$userInfo = M('User')->where('id='.$cookieId[1])->find();
			return $this->loginLocal($userInfo['email']);
		}
	}
	//成功登录后，设置Session和Cookie
	static function setSessionAndCookie4User($user, $remember = false) {
		//dumpecho 'run setSessionAndCookie4User '.C('COOKIE_FLAG_USER');
		$_SESSION['mid']			=	$user['id'];
		$_SESSION['uname']			=	$user['uname'];
		$_SESSION['login_status']	=	$user['role'];
		$_SESSION['userInfo']	=	$user;
		//如果需要在登陆的session中添加额外信息，在此添加
		$remember ? 
			cookie(C('COOKIE_FLAG_USER'),base64_encode('USER.'.$user['id']),(3600*24*365)) : 
			cookie(C('COOKIE_FLAG_USER'),base64_encode('USER.'.$user['id']),(3600*2));
	}
	
	/**
	 * 登陆到本地 (密码为false时仅验证Email)  该方法暂时没有用到
	 * 当使用cookie自动登陆时，不需要密码。所以(密码为false时仅验证Email)
	 * @param string         $email
	 * @param string|boolean $password
	 * @return boolean
	 */
	public function loginLocal($email,$password=false) {
		// 获取账号信息
		$user	=	$this->getLocalUser($email,$password);
		
		if(!$user) {
			return false;
		}else{
			//注册session
			
			//登录记录
			$this->recordLogin($user['id']);
			return true;
		}
	}
	
	/**
	 * 联盟登录
	 * @param string         $email
	 * @param string|boolean $password
	 * @return boolean
	 */
	public function loginAgent($email,$password=false) {
		$user = $this->getLocalUser($email,$password);
		//echo "loginAgent".$_SESSION['login_status']."<br>";
		//dump($user);
		if($user['role']!='agent'){
			$result = false;
			$this->logoutLocal();
		}else{
			// 获取账号信息
			$user	=	model('Agent')->getAgent($user['id']);
			//dump($user);
			//登录记录
			$this->recordLogin($user['id']);
			$this->setSessionAndCookie4User($user);
			$result = true;
		}
		return $result;
	}
	
	
	/**
	 * 检查是否登陆后台
	 */
	public function isLoggedAdmin() {
		return $_SESSION['QuickAdmin'] == 1 && !empty($_SESSION['adminId']);
	}
	
	/**
	 * 登陆后台
	 * 
	 * @param string $email    用户Email,不能和用户ID同时为空
	 * @param string $password 未加密的密码,不能为空
	 * @return boolean
	 */
	public function loginAdmin($email = NULL, $password) {
		// uid和email必须至少有一个为合法值，密码必须不为空
		if ( empty($email) || empty($password) ) {
			return false;
		}
		
		// 检查用户名/密码
		//$adminId > 0		&& $map['id']	 = $adminId;
		!empty($email)	&& $map['email'] = $email;
		$map['password'] = md5($password);
		$map['enable'] = 'Y';
		$map['is_delete'] = 'N';
		if ( ! ($admin = M('Admin')->where($map)->find()) ) {
			unset($_SESSION['QuickAdmin']);
			unset($_SESSION['adminId']);
			unset($_SESSION['adminName']);
			unset($_SESSION['adminEmail']);
			return false;
		}
		
		// 检查是否拥有admin/Index/index权限
		//if ( service('SystemPopedom')->hasPopedom($user['uid'], 'admin/Index/index', false) ) {
		$_SESSION['QuickAdmin']	= 1;
		$_SESSION['adminId']			= $admin['id'];
		$_SESSION['adminEmail']			= $admin['email'];
		$_SESSION['adminName']			= $admin['uname'];
			
		//登录记录
		//$this->recordLogin($user['uid']);
		return true;
		/**
		// 检查是否拥有admin/Index/index权限
		if ( service('SystemPopedom')->hasPopedom($user['uid'], 'admin/Index/index', false) ) {
			$_SESSION['ThinkSNSAdmin']	= 1;
			$_SESSION['mid']			= $user['uid'];
			$_SESSION['uname']			= $user['uname'];

			//登录记录
			$this->recordLogin($user['uid']);
			return true;
		}else {
			unset($_SESSION['ThinkSNSAdmin']);
			return false;
		}
		**/
	}
	
	
	

	/**
	 * 管理员销注
	 * @return void
	 */
	public function logoutAdmin() {
		//注销session
		unset($_SESSION['QuickAdmin']);
		unset($_SESSION['adminId']);
		unset($_SESSION['adminEmail']);
		unset($_SESSION['adminName']);
		unset($_SESSION['ADMIN_VERIFYCODE']);
	}
	
	
	/**
	 * 注销本地登录
	 * @return void
	 */
	public function logoutLocal($ifclearcooie=true) {
		//注销session
		unset($_SESSION['mid']);
		unset($_SESSION['uname']);
		unset($_SESSION['userInfo']);
		unset($_SESSION['login_status']);
		//unset($_SESSION);
		//注销cookie
		if($ifclearcooie)cookie(C('COOKIE_FLAG_USER'),NULL);
	}
	
	/**
	 * 登录记录
	 * 
	 * @param int $uid 用户ID
	 */
	public function recordLogin($uid) {
		$data['uid']	= $uid;
		$data['ip']		= get_client_ip();
		$data['place']	= convert_ip($data['ip']);
		$data['ctime']	= time();
		M('LoginRecord')->add($data);
	}

	
	/**
	 * 商户管理系统登录
	 * 
	 * @param string $email    用户Email,不能和用户ID同时为空
	 * @param string $password 未加密的密码,不能为空
	 * @return boolean
	 */
	public function loginPartner($pid,$role='admin', $password=false) {
		$partner = service('Brand')->select4UserByPid($pid);
		Log::record('PassportService.loginPartner('.$pid.",".$role.",". $password.')',Log::DEBUG,Log::FILE);
		Log::record('PassportService.loginPartner()->partner='.parseAry2Str($partner),Log::DEBUG,Log::FILE);
		Log::save();
		if(empty($partner)) {
			return false;
		}else{
			if($password !== false) {
				if($role=='admin'){
					if(md5($password)!=$partner['admin_password']){
						return false;
					}
				}else{
					if(empty($partner['checker_password'])){
						//表示不需要密码验证员即可登录
					}else{
						if(md5($password)!=$partner['checker_password']){
							return false;
						}
					}
				}
			}
			
			//如果为分店，则读取相应总店信息
			if($partner['parent_id']!=0){
				$parentPartner = D('Partner','Admin')->selectById($partner['parent_id']);
				//dump($parentPartner);
				$partner['brand_icon']=$parentPartner['brand_icon'];
			}
			$_SESSION['partnerInfo']	=	serialize($partner);
			PassportService::setSessionAndCookie4SH($partner['id'], $role , $partner['title'] ,$partner['parent_id']);
			//ump($_SESSION);
			return $partner;
		}
	}
	
	//成功登录后，设置Session和Cookie
	static function setSessionAndCookie4SH($pid, $role , $title ,$parent_id, $remember = false) {
		$_SESSION['QuickPartner']	=	'QuickPartner';
		$_SESSION['qp_id']			=	$pid;
		if($role=='admin')$_SESSION['qp_role']	=	'admin';
		else $_SESSION['qp_role']	=	'checker';
		$_SESSION['qp_title']		=	$title;
		if(empty($parent_id))$_SESSION['qp_is_root']		=	'yes';//是否为根店铺
		if(empty($parent_id))$parent_id=$pid;
		$_SESSION['qp_parent_id']	=	$parent_id;
		
		//如果需要在登陆的session中添加额外信息，在此添加
		$remember ? 
			cookie(C('COOKIE_FLAG_PARTNER'),base64_encode('PARTNER.'.$pid.'.'.$role),(3600*24*365)) : 
			cookie(C('COOKIE_FLAG_PARTNER'),base64_encode('PARTNER.'.$pid.'.'.$role),(3600*2));
	}
	
	/**
	 * 验证商户管理系统是否已登录
	 * @return boolean
	 */
	public function isLoggedPartner(){
		$_cookie_partner	=	t(cookie(C('COOKIE_FLAG_PARTNER')));
		$_session_qp_id		=	intval($_SESSION['qp_id']);
		
		// 验证本地系统登录
		if($_session_qp_id){
			return true;
		}elseif ($_cookie_partner){
			return $this->cookieLoginPartner($_cookie_partner);
		}else{
			return false;
		}
	}
	/**
	 * 使用cookie登陆商户管理系统
	 * 
	 * @param string $cookieId
	 * @return boolean
	 */
	public function cookieLoginPartner($cookieId){
		$cookieId = explode( '.', base64_decode($cookieId) );
		if ($cookieId[0] !== 'PARTNER') {
			return false;
		}else {
			$partnerInfo = service('Brand')->getById($cookieId[1]);
			return $this->loginPartner($partnerInfo['id'],$cookieId[2]);
		}
	}

	/**
	 * 注销本地登录商户管理系统
	 * @return void
	 */
	public function logoutLocalPartner() {
		//注销session
		unset($_SESSION['QuickPartner']);
		unset($_SESSION['qp_id']);
		unset($_SESSION['qp_role']);
		unset($_SESSION['qp_title']);
		unset($_SESSION['qp_parent_id']);
		unset($_SESSION['qp_is_root']);
		//注销cookie
		cookie(C('COOKIE_FLAG_PARTNER'),NULL);
	}
	
	/* 后台管理相关方法 */
	
	// 运行服务，系统服务自动运行
	public function run(){
		return;
	}

	//启动服务，未编码
	public function _start(){
		return true;
	}

	//停止服务，未编码
	public function _stop(){
		return true;
	}

	//卸载服务，未编码
	public function _install(){
		return true;
	}

	//卸载服务，未编码
	public function _uninstall(){
		return true;
	}
}
?>